// internal/interfaces/middleware/auth.go
package middleware

import (
	"gLottery/pkg/jwt"
	"github.com/gin-gonic/gin"
	jwtOn "github.com/golang-jwt/jwt/v4" // 确保导入v4版本
	"net/http"
	"strings"
)

type Auth struct {
	jwtService jwt.JWTService
}

func NewAuth(jwtService jwt.JWTService) *Auth {
	return &Auth{jwtService: jwtService}
}

func (a *Auth) Validate() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := extractToken(c)
		if tokenString == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
			return
		}

		token, err := a.jwtService.ValidateToken(tokenString)
		if err != nil || !token.Valid {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			return
		}

		// 使用类型断言获取claims
		claims, ok := token.Claims.(jwtOn.MapClaims)
		if !ok {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
			return
		}

		userID, ok := claims["user_id"].(float64) // JWT数字默认解码为float64
		if !ok {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid user_id"})
			return
		}

		c.Set("userID", uint(userID))
		c.Next()
	}
}

func extractToken(c *gin.Context) string {
	bearerToken := c.GetHeader("Authorization")
	if len(strings.Split(bearerToken, " ")) == 2 {
		return strings.Split(bearerToken, " ")[1]
	}
	return ""
}
